const { query } = require('../config/database');

class User {
  /**
   * 根据邮箱查找用户
   * @param {string} email - 用户邮箱
   * @returns {Object|null} 用户信息或null
   */
  static async findByEmail(email) {
    try {
      const sql = `
        SELECT 
          user_id as userId,
          email,
          password,
          nick_name as nickName,
          avatar,
          status,
          created_at as createdAt,
          updated_at as updatedAt
        FROM users 
        WHERE email = ?
      `;
      
      const users = await query(sql, [email]);
      return users.length > 0 ? users[0] : null;
    } catch (error) {
      console.error('查找用户失败:', error);
      throw new Error('数据库查询失败');
    }
  }

  /**
   * 根据用户ID查找用户
   * @param {string} userId - 用户ID
   * @returns {Object|null} 用户信息或null
   */
  static async findByUserId(userId) {
    try {
      const sql = `
        SELECT 
          user_id as userId,
          email,
          nick_name as nickName,
          avatar,
          status,
          created_at as createdAt,
          updated_at as updatedAt
        FROM users 
        WHERE user_id = ?
      `;
      
      const users = await query(sql, [userId]);
      return users.length > 0 ? users[0] : null;
    } catch (error) {
      console.error('查找用户失败:', error);
      throw new Error('数据库查询失败');
    }
  }

  /**
   * 创建新用户
   * @param {Object} userData - 用户数据
   * @returns {Object} 创建的用户信息
   */
  static async create(userData) {
    try {
      const { userId, email, password, nickName, avatar = null, status = 1 } = userData;
      
      const sql = `
        INSERT INTO users (user_id, email, password, nick_name, avatar, status)
        VALUES (?, ?, ?, ?, ?, ?)
      `;
      
      await query(sql, [userId, email, password, nickName, avatar, status]);
      
      // 返回创建的用户信息（不包含密码）
      return await User.findByUserId(userId);
    } catch (error) {
      console.error('创建用户失败:', error);
      if (error.code === 'ER_DUP_ENTRY') {
        throw new Error('邮箱已存在');
      }
      throw new Error('创建用户失败');
    }
  }

  /**
   * 更新用户状态
   * @param {string} userId - 用户ID
   * @param {number} status - 状态值
   * @returns {boolean} 更新是否成功
   */
  static async updateStatus(userId, status) {
    try {
      const sql = `
        UPDATE users 
        SET status = ?, updated_at = CURRENT_TIMESTAMP
        WHERE user_id = ?
      `;
      
      const result = await query(sql, [status, userId]);
      return result.affectedRows > 0;
    } catch (error) {
      console.error('更新用户状态失败:', error);
      throw new Error('更新用户状态失败');
    }
  }

  /**
   * 更新用户信息
   * @param {string} userId - 用户ID
   * @param {Object} updateData - 要更新的数据
   * @returns {Object|null} 更新后的用户信息
   */
  static async update(userId, updateData) {
    try {
      const allowedFields = ['nick_name', 'avatar', 'status'];
      const updateFields = [];
      const updateValues = [];
      
      // 构建更新字段
      Object.keys(updateData).forEach(key => {
        if (allowedFields.includes(key)) {
          updateFields.push(`${key} = ?`);
          updateValues.push(updateData[key]);
        }
      });
      
      if (updateFields.length === 0) {
        throw new Error('没有有效的更新字段');
      }
      
      updateValues.push(userId);
      
      const sql = `
        UPDATE users 
        SET ${updateFields.join(', ')}, updated_at = CURRENT_TIMESTAMP
        WHERE user_id = ?
      `;
      
      const result = await query(sql, updateValues);
      
      if (result.affectedRows > 0) {
        return await User.findByUserId(userId);
      }
      
      return null;
    } catch (error) {
      console.error('更新用户信息失败:', error);
      throw new Error('更新用户信息失败');
    }
  }
}

module.exports = User;